﻿// this background script is used to invoke desktopCapture API
// to capture screen-MediaStream.

var screenOptions = ['screen', 'window'];
// var screenOptions = ['screen'];
var RTC_PAGE_MSG_TYPE = 'RTC-SD-PAGE';
var RTC_EXT_MSG_TYPE = 'RTC-SD-EXT';

chrome.runtime.onConnect.addListener(function (port) {
    port.onMessage.addListener(portOnMessageHanlder);
    
    // this one is called for each message from "content-script.js"
    function portOnMessageHanlder(msg) {
        
        if(!msg.type || msg.type !== RTC_PAGE_MSG_TYPE) return;
        if(!msg.evname) return;

        console.log('rtc-sd-bk: msg=', msg);

        var opt = screenOptions;
        if(msg.screenOptions) {
            opt = msg.screenOptions;
        }
        if(msg.evname === 'chooseDesktopMedia') {
            chrome.desktopCapture.chooseDesktopMedia(opt, port.sender.tab, function(streamId, options){
                // if "cancel" button is clicked
                if(!streamId || !streamId.length) {
                    return port.postMessage({type:RTC_EXT_MSG_TYPE, evname:'onAccessDenied', tsxId:msg.tsxId});
                }

                // "ok" button is clicked
                return port.postMessage({type:RTC_EXT_MSG_TYPE
                    , evname:'onAccessApproved'
                    , streamId:streamId
                    , tsxId:msg.tsxId
                });
            });
        }
    }


});
